package com.owc.service.impl.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.owc.common.enums.ExceptionEnum;
import com.owc.common.exception.BadRequestException;
import com.owc.common.tool.BeanUtils;
import com.owc.common.tool.DateUtils;
import com.owc.common.tool.UtilsService;
import com.owc.dao.ProductAttachMapper;
import com.owc.dao.ProductMapper;
import com.owc.domain.BaseResult;
import com.owc.domain.PageBean;
import com.owc.domain.dto.ProductDetailDTO;
import com.owc.domain.dto.admin.OrderDTO;
import com.owc.domain.dto.admin.OrderListDTO;
import com.owc.domain.dto.admin.ProductWithAdminDTO;
import com.owc.domain.entity.Order;
import com.owc.domain.entity.Product;
import com.owc.domain.entity.ProductAttach;
import com.owc.domain.entity.Token;
import com.owc.domain.vo.admin.ProductAttachVo;
import com.owc.domain.vo.admin.ProductModel;
import com.owc.domain.vo.admin.ProductQueryVo;
import com.owc.service.OwcService;
import com.owc.service.admin.ProductService;
import com.owc.service.app.OrderService;
import com.owc.service.app.WalletService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author xiaom
 * @Date 2020/2/28 13:41
 * @Version 1.0.0
 * @Description <>
 **/
@Service
public class ProductServiceImpl implements ProductService {

    @Resource
    private ProductMapper productMapper;
    @Resource
    private ProductAttachMapper productAttachMapper;

    @Autowired
    private OwcService owcService;
    @Autowired
    private WalletService walletService;
    @Autowired
    private OrderService orderService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(ProductModel productModel) {

        //附加属性
        ProductAttach productAttach = BeanUtils.transformFrom(productModel,ProductAttach.class);
        //基本信息
        Product product = BeanUtils.transformFrom(productModel,Product.class);
        if(productAttach == null || product == null){
            throw new BadRequestException(ExceptionEnum.UNKNOWN_ERR);
        }
        productAttachMapper.insert(productAttach);

        product.setExpandId(productAttach.getId());

        //根据tokenName获取对应的tokenId
        Token token = walletService.getTokenByName(productModel.getTokenName());
        Token incomeToken = walletService.getTokenByName(productModel.getIncomeName());
        if(token == null || incomeToken == null){
            throw new BadRequestException(ExceptionEnum.INVALID_TOKEN_ERR);
        }else{
            product.setTokenId(token.getId());
            product.setIncomeId(incomeToken.getId());
        }
        //如果标签不为空,检验标签是否符合规则
        validTags(productModel.getTags());

        //注入基本信息
        owcService.injectDefaultAttr(product);
        productMapper.insert(product);

        return true;
    }

    @Override
    public ProductDetailDTO detail(Long id) {
        return productMapper.selectDetailByProduceId(id);
    }

    @Override
    public Boolean update(ProductAttachVo productAttachVo) {
        //获取拓展信息的id
        Product product = productMapper.selectByPrimaryKey(productAttachVo.getId());
        Assert.notNull(product,"不存在的产品");
        ProductAttach productAttach = BeanUtils.transformFrom(productAttachVo,ProductAttach.class);
        if(productAttach == null){
            return false;
        }
        if(productAttachVo.getIntroduction() != null && productAttachVo.getIntroduction().isEmpty()){
            throw new BadRequestException("产品介绍不能为空");
        }
        productAttach.setUpdateTime(DateUtils.formatYMDHMS(new Date()));
        productAttach.setId(product.getExpandId());
        productAttachMapper.updateByPrimaryKeyNotNull(productAttach);
        return true;
    }

    @Override
    public PageBean<ProductWithAdminDTO> list(ProductQueryVo productQueryVo) {
        productQueryVo.loadStatus();

        PageHelper.startPage(productQueryVo.getPageIndex(),productQueryVo.getPageSize());
        List<ProductWithAdminDTO> list = productMapper.selectByFilter(productQueryVo);
        PageInfo<ProductWithAdminDTO> pageInfo = new PageInfo<>(list);
        return PageBean.pageBean(pageInfo.getTotal(),list);
    }

    @Override
    public BaseResult<OrderListDTO> getProductOrderList(Long id, Integer pageIndex, Integer pageSize) {
        OrderListDTO orderListDTO = new OrderListDTO();
        PageInfo<Order> pageInfo = orderService.getOrderListByProductId(id,pageIndex,pageSize);

        if(pageInfo.getTotal() == 0){
            return BaseResult.success(null);
        }

        List<Order> list = pageInfo.getList();
        orderListDTO.setOrders(BeanUtils.coventObject(list, OrderDTO.class));

        //获取累计购买金额
        orderListDTO.setTotalAmount(orderService.statisticsAmount(id));
        return BaseResult.success(orderListDTO,pageInfo.getTotal());
    }

    private void validTags(String tags) {

        if(UtilsService.isEmpty(tags)){
           return;
        }
        String[] arrays = tags.split(",");
        for (String array : arrays) {
            if(UtilsService.String_length(array) > 8){
                throw new BadRequestException("标签超出最大字符");
            }
        }
    }
}
